package cn.trigram.uuid;

import cn.trigram.uuid.tw.SnowflakeGenerator;
import java.util.Objects;

public class SnowflakeUidUtil {

  private final UidConfigHelper helper = new UidConfigHelper(
      "snowflake");

  private static SnowflakeUidUtil instance;

  private final SnowflakeGenerator generator;

  private SnowflakeUidUtil() {

    generator = new SnowflakeGenerator(helper.getInt("tw_worker_id", 0),
        helper.getInt("tw_data_center_id", 0));
  }


  public static SnowflakeUidUtil getInstance() {

    if (instance == null) {
      synchronized (SnowflakeUidUtil.class) {
        if (instance == null) {
          instance = new SnowflakeUidUtil();
        }
      }
    }
    return instance;
  }


  /**
   * 获取批次号 基于snowflake的简单实现，简单通过等待时间来避免时间回拨问题
   */
  public long getUid() {

    return generator.nextId();
  }

  public String parseUid(Long uid) {

    Objects.requireNonNull(uid, "UID不能为空");
    return generator.parseUid(String.valueOf(uid));
  }

}
